<?php
include '../config/auth.php';
//连接数据库
try {
    function success(){
        $result=[
            'error' => 0,
            'message' => '成功'
        ];
        return json_encode($result);
    }
    function error($mag){
        $data = [
            'error' => 1,
            'message' => $mag
        ];
        return json_encode($data);
    }

    //获取传过来的数据
    $username=$_SESSION['user'];
    $password=$_POST['password'];
    $confirm=$_POST['confirm'];
    $nickname=$_POST['nickname'];

    //文件上传
    if(!isset($_FILES['image'])){
        die('无文件上传');
    }
    if($_FILES['image']['error']!=0){
        die('文件上传出错');
    }
    $allow=[
        'image/jpg',
        'image/png',
        'image/gif'
    ];
    if(!in_array($_FILES['image']['error'],$allow)){
        die('禁止上传该类型');
    }
    $file_name=$_FILES['image']['name'];
    $file_name=explode('.',$file_name)[1];
    $file_name=$username.'.'.$file_name;
    $file_name='../upload/'.$file_name;
    move_uploaded_file($_FILES['image']['tmp_name'],$file_name);
    $_SESSION['file']=$file_name;

    //连接数据库
    $config = include '../config/db.php';
    $db = new PDO($config['dsn'],$config['username'],$config['password']);

    $statement = $db->prepare('select * from user where username=:username');
    $statement->execute([
        ':username'=> $username
    ]);
    $result=$statement->fetch();
    if($file_name ==$result['path']){
        die(error('照片已存在'));
    }

    if(empty($_POST['password'])){
        die(error('密码不能为空'));
    }

    if(empty($_POST['confirm'])){
        die(error('确认密码不能为空'));
    };

    if(empty($_POST['nickname'])){
        die(error('昵称不能为空'));
    }

    if(empty($_FILES['image'])){
        die(error('头像不能为空'));
    }
    if($password!=$confirm){
        die(error('密码不一致！'));
    }
    $statement=$db->prepare('update user set password=:password,nickname=:nickname,path=:path where username=:username');
    $result=$statement->execute([':username'=>$username,':password'=>$password,':nickname'=>$nickname,':path'=>$file_name]);
    echo success();
} catch (PDOException $e) {
    echo 'Connection failed';
}